<template>
    <el-card class="box-card">
        <!-- 卡片顶部添加品牌的按钮 -->
        <el-button type="primary" icon="Plus" @click="addTrademark">添加品牌</el-button>
        <!-- 表格组件: 用于展示已有的平台数据-->
        <!-- table
            --border:可以设置表格纵向是否有边缘
            table-column
         -->
        <el-table :data="trademarkArr" class="my-2 " border>
            <el-table-column label="序号" property="id" width="100" align="center"></el-table-column>
            <el-table-column label="品牌名称" property="tmName" align="center"></el-table-column>
            <el-table-column label="品牌logo" property="logoUrl">
                <template #="{ row }" align="center">
                    <img :src="row.logoUrl" class="h-20 w-20">
                </template>
            </el-table-column>
            <el-table-column label="品牌操作" align="center">
                <template #="{ row }">
                    <el-button size="small" type="warning" icon="Edit" @click="updateTrademark(row)"></el-button>
                    <!-- 删除 -->
                    <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" icon="Delete"
                        icon-color="#626AEF" title="是否删除数据" @confirm="removeTradeMark(row.id)">
                        <template #reference>
                            <el-button size="small" type="danger" icon="Delete" ></el-button>
                        </template> 
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器组件 
            pagination
            v-model:current-page:设置分页器当前的页码
            v-model:page-size:设置每页展示的数据条数
            page-sizes:用于设置下拉菜单的数据
            background:设置分页器按钮的的背景颜色
            layout:可以设置分页器六个子组件 布局的调整
        -->
        <div class="demo-pagination-block">
            <el-pagination @current-change="changePageNo" :pager-count="9" v-model:current-page="pageNo"
                v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]" :background="true"
                layout=" prev, pager, next, jumper,->, total, sizes," :total="total" />
        </div>
    </el-card>
    <!-- 对话框组件 在添加品牌与与已有的品牌的业务时候使用结构 -->
    <!-- v-model:属性用户控制对话框的显示或隐藏的true显示flase -->
    <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
        <!-- 表单 -->
        <el-form style="width:80%;" label-width="auto" :model="trademarkParams" :rules="rules" ref="formRef">
            <el-form-item label="品牌名称" prop="tmName">
                <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
            </el-form-item>
            <el-form-item label="品牌LOGO" prop="logoUrl">
                <!-- upload组件属性:action 上传路径书写/api,代理服务器不发送这次post请求-->
                <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="true"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />    
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <!-- 具名插槽:footer -->
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="confirm">
                    确定
                </el-button>
            </span>
        </template>

    </el-dialog>
</template>

<script lang="ts" setup>    
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
//引入组合式API函数ref
import { ref, onMounted, reactive } from "vue"
import { reqHasTrademark, reqAddOrUpdateTrademark,reqDeleteTrademark } from '../../../api/product/trademark/index'
import { Records, TradeMark } from '../../../api/product/trademark/type'
//当前的页面
let pageNo = ref<number>(1)
//定义每一页展示多少条数据
let limit = ref<number>(9)
//总页数
let total = ref<number>()
// 存储已有品牌的数据   
let trademarkArr = ref<Records>([])
//控制对话框的显示或者隐藏
let dialogFormVisible = ref<boolean>()
//定义收集新增品牌的数据
let trademarkParams = reactive<TradeMark>({
    tmName: "",
    logoUrl: ''
})

//获取已有品牌的接口封装为一个函数:在任何情况下向获取数据,调用次函数即可
const getHasTrademark = async () => {
    let result = await reqHasTrademark(pageNo.value, limit.value)
    if (result.code == 200) {
        total.value = result.data.total
        trademarkArr.value = result.data.records
    }
    // console.log(trademarkArr);
}
//组件挂载完毕钩子 发一次请求,获取第一页,一页三个已有品牌数据
onMounted(() => {
    getHasTrademark()
})
const changePageNo = () => {
    //当前页码发生变化的时候再次发送请求获取对应的已有品牌数据展示
    getHasTrademark()
}
//添加品牌的回调
const addTrademark = () => {
    dialogFormVisible.value = true
    //清空收集的数据
    trademarkParams.id = 0;
    trademarkParams.logoUrl = ''
    trademarkParams.tmName = ''
    formRef.value?.resetFields()
}
const formRef = ref()
//修改品牌的回调
const updateTrademark = (row) => {
    dialogFormVisible.value = true
    trademarkParams.id = row.id
    trademarkParams.tmName = row.tmName
    trademarkParams.logoUrl = row.logoUrl
    formRef.value?.resetFields()

}
//cancel
const cancel = () => {
    // 对话框隐藏
    dialogFormVisible.value = false

}
//confirm
const confirm = async () => {
    //在发请求之前,要对整个表单进行校验
    //调用这个方法进行全部的表单项校验,如果校验全部通过,在执行后面的语法
    await formRef.value.validate();
    let result: any = await reqAddOrUpdateTrademark(trademarkParams)
    console.log(result);

    if (result.code == 200) {
        dialogFormVisible.value = false

        // 添加品牌成功!
        ElMessage({
            showClose: true,
            message: trademarkParams.id ? '修改品牌成功!' : '添加品牌成功!',
            type: 'success',
        });
        //再次发请求获取已有的全部品牌数据
        getHasTrademark()
    } else {
        dialogFormVisible.value = false
        // 添加品牌失败!
        ElMessage({
            showClose: true,
            message: trademarkParams.id ? '修改品牌失败!' : '添加品牌失败!',
            type: 'error',
        })
    }
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/gif') {
        if (rawFile.size / 1024 / 1024 < 4) {
            return true
        } else {
            ElMessage.error('上传文件大小小于4MB')
            return false
        }
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(uploadFile);
    trademarkParams.logoUrl = response.data
    formRef.value.clearValidate();

}
//品牌校验自定义的校验方法
const validatorTmName = (rule: any, value: any, callback: any) => {
    console.log(rule);
    
    //当表单元素触发blur时候,会触发此方法
    if (value.trim().length >= 2) {
        callback()
    } else {
        
        callback(new Error('请输入品牌名称!'))
    }
}
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
    console.log(rule);

    if (value === '') {
        callback(new Error('请上传品牌LOGO!'))
    } else {
        callback()
    }
}
//表单校验规则
const rules = {
    //required:表这个字段务必要校验,是表单项前面出现星号
    //trigger:表触发检验规则时机[blur,change]
    tmName: [{ required: true, validator: validatorTmName, trigger: 'blur' }],
    logoUrl: [{ required: true, validator: validatorLogoUrl, trigger: 'change' }],
}
const removeTradeMark = async (id) => {
    let result: any = await reqDeleteTrademark(id)
    if (result.code == 200) {
        ElMessage({
            showClose: true,
            message: '删除品牌成功!',
            type: 'success',
        });  
        getHasTrademark(trademarkArr.value.length > 1 ? pageNo.value : pageNo-1)

    } else {
        ElMessage({
            showClose: true,
            message: '删除品牌失败!',
            type: 'error',
        });
    }
}
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>